package org.homonoia.worker.sql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.homonoia.model.task.Task;

public class SearchMySQL implements SearchSQL {

    private static final Logger log = Logger.getLogger(SearchMySQL.class);

    public void checkForRowIDColumn(Statement stmt, final Task task) throws SQLException {
	String colCheck = "SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = '"
		+ task.getTable() + "' AND COLUMN_NAME = 'row_id';";

	ResultSet colRs = stmt.executeQuery(colCheck);
	if (!colRs.first()) {
	    String rowIdAdd = "ALTER TABLE " + task.getTable()
		    + " ADD row_id MEDIUMINT NOT NULL PRIMARY KEY AUTO_INCREMENT;";
	    stmt.execute(rowIdAdd);
	}
	colRs.close();
    }

    public int getColumnCount(Statement stmt, final Task task) throws SQLException {
	int colCount = 0;

	String colNum = "SELECT Count(*) AS NumCols FROM information_schema.COLUMNS WHERE TABLE_NAME = '"
		+ task.getTable() + "';";

	ResultSet colCountRs = stmt.executeQuery(colNum);
	if (colCountRs.first()) {
	    colCount = colCountRs.getInt("NumCols");
	} else {
	    throw new SQLException("No columns in results.");
	}
	colCountRs.close();

	return colCount;
    }

    public String generateStatement(final Task task) {
	String sql = "SELECT * FROM " + task.getTable() + " WHERE row_id BETWEEN "
		+ task.getStartRow() + " AND " + task.getEndRow() + " AND " + task.getColumn()
		+ " IN (";

	for (int i = 0; i < task.getSearchTerms().size(); ++i) {
	    sql += "'" + task.getSearchTerms().get(i) + "'";
	    if (i < task.getSearchTerms().size() - 1) {
		sql += ",";
	    }
	}

	sql += ");";

	return sql;
    }

}
